package com.dalei.vdserver.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.dalei.vdserver.model.InvalidItems;

public class InvalidItemsDaoImpl extends JdbcDaoSupport implements
		InvalidItemsDao {

	@Override
	@SuppressWarnings("unchecked")
	public List<Integer> getInvalidItemsByFid(int fid) {
		// TODO Auto-generated method stub
		final String sql = "SELECT _invalidItemId FROM vds_invalid_items"
				+ "WHERE _fid=? ORDER BY _invalidItemId";
		List<Integer> invalidItems = null;
		try {
			invalidItems = getJdbcTemplate().query(sql, new Object[] { fid },
					new RowMapper() {

						@Override
						public Object mapRow(ResultSet rs, int rowNum)
								throws SQLException {
							// TODO Auto-generated method stub
							return rs.getInt("_invalidItemId");
						}
					});
		} catch (DataAccessException e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
		return invalidItems;
	}

	@Override
	public int[] addInvalidItems(InvalidItems invalidItems) {
		// TODO Auto-generated method stub
		final String sql = "INSERT INTO vds_invalid_items (_fid, _invalidItemId) "
				+ "VALUES (?, ?)";
		final int fid = invalidItems.getFid();
		final List<Integer> invalidItemsList = invalidItems.getInvalidItems();
		
		int[] rowAffected = null;
		try {
			rowAffected = getJdbcTemplate().batchUpdate(sql,
					new BatchPreparedStatementSetter() {

						@Override
						public void setValues(PreparedStatement ps, int i)
								throws SQLException {
							// TODO Auto-generated method stub
							ps.setInt(1, fid);
							ps.setInt(2, invalidItemsList.get(i));
						}

						@Override
						public int getBatchSize() {
							// TODO Auto-generated method stub
							return invalidItemsList.size();
						}
					});
		} catch (DataAccessException e) {
			// TODO: handle exception
			e.printStackTrace();
			clearInvalidItems(fid);
			return null;
		}
		return rowAffected;
	}

	@Override
	public int clearInvalidItems(int fid) {
		// TODO Auto-generated method stub
		String sql = "DELETE FROM vds_invalid_items WHERE _fid=?";
		int rowAffected = 0;
		try {
			rowAffected = getJdbcTemplate().update(sql, new Object[] { fid });
		} catch (DataAccessException e) {
			// TODO: handle exception
			e.printStackTrace();
			return -1;
		}
		return rowAffected;
	}
}
